<?php

namespace app\common\controller;

use app\admin\service\UserService;
use app\BaseController;
use app\common\message\Mail;
use app\model\AreasModel;
use app\model\AuthRuleModel;
use app\model\CompanyModel;
use app\model\ConfigModel;
use app\model\DepartmentModel;
use app\model\PlatformAuthRuleModel;
use app\model\PlatformModel;
use app\model\RoleModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\TaskUserModel;
use app\model\UnitModel;
use app\model\UserModel;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Queue;

class Login extends BaseController
{
    protected UserModel $mode;
    protected CompanyModel $CompanyModel;
    protected PlatformModel $PlatformModel;
    protected UnitModel $UnitModel;


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new UserModel();
        //公司
        $this->CompanyModel = new CompanyModel();
        //平台
        $this->PlatformModel = new PlatformModel();
        //单位
        $this->UnitModel = new UnitModel();
    }

    /**
     * 获取公司信息
     * @return bool|string
     */
    public function getCompanyInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'login_jump|登录跳转' => 'require'
            ]);
            $CompanyModel = new CompanyModel();
            $info = $CompanyModel->field('id,name,logo,platform_name,abbreviation,login_jump')
                ->where('login_jump','=', $param['login_jump'])->cache(true,60)->find();
            if ($info){
                $info = $info->toArray();
                $info['name'] = $info['name'].' All Rights Reserved. 湘ICP备14001762号-1';
                $info['abbreviation'] = 'Copyright ©2025 - '.$info['abbreviation'];
            }else{
                $info = [
                    'id' => 0,
                    'logo' => '/static/fdkj_logo.png',
                    'platform_name' => '福地科技健康云联心理平台',
                    'name' => '长沙福地科技有限公司 All Rights Reserved. 湘ICP备14001762号-1',
                    'abbreviation' => 'Copyright ©2025 - 福地',
                    'login_jump' => 'login'
                ];
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取用户完整信息
     * @param $user
     * @return bool|string
     */
    public function getUserInfo($user): bool|string
    {
        try {
            switch ($user['type']) {
                case 0:
                    //admin
                    $user['subset_unit'] = $this->UnitModel->column('id');
                    break;
                case 1:
                    //公司
                    $user['company'] = $this->CompanyModel->find($user['company_id']) ?? [];
                    //判断使用状态
                    if (!$this->UseStatus($user['company'])) throw new \Exception('公司已过使用期限/已被禁用！');
                    $this->SubsetUnit($user);
                    break;
                case 2:
                    //平台
                    $user['platform'] = $this->PlatformModel->where([
                        ['company_id', '=', $user['company_id']],
                        ['areas_id', '=', $user['areas_id']]
                    ])->find() ?? [];
                    //判断使用状态
                    if (!$this->UseStatus($user['platform'])) throw new \Exception('平台已过使用期限/已被禁用！');
                    $user['platform_id'] = $user['platform']['id'] ?? 0;
                    $this->SubsetUnit($user);
                    break;
                case 3:
                case 4:
                    //单位
                    $user['unit'] = $this->UnitModel->with(['UnitBanner'])->find($user['unit_id']) ?? [];
                    //判断使用状态
                    if (!$this->UseStatus($user['unit'])) throw new \Exception('单位已过使用期限/已被禁用！');
                    break;
                case 5:
                    //社区
                    $user['platform'] = $this->PlatformModel->where([
                        ['company_id', '=', $user['company_id']],
                        ['areas_id', '=', $user['areas_id']]
                    ])->find() ?? [];
                    //判断使用状态
                    if (!$this->UseStatus($user['platform'])) throw new \Exception('平台已过使用期限/已被禁用！');
                    $user['platform_id'] = $user['platform']['id'] ?? 0;
                    $this->SubsetUnit($user);
            }
            if (!is_array($user)){
                $user = $user->toArray();
            }
            if (!$this->LoginLog($user)) throw new \Exception('登录失败！');
            $user['token'] = generateLoginToken($user, 'user_');
            switch ($user['type']) {
                case 0:
                    //顶级超管
                    $user['company'] = [
                        'name' => '心理云平台',
                        'start_time' => 1740385295,
                        'end_time' => 2055909893,
                        'admin_num' => 999999,
                        'consultant_num' => 999999,
                        'user_num' => 999999,
                        'company_num' => 999999,
                        'index_logo' => env('SETTING.SOFTWARE_LOGO'),
                        'logo' => env('SETTING.UNIT_ICON'),
                        'photo_one' => env('SETTING.PHOTO_ONE'),
                        'photo_two' => env('SETTING.PHOTO_TWO'),
                        'banner' => env('SETTING.PC_BANNER'),
                    ];
                    $this->getPlatformAuthRule($user);
                    break;
                case 1:
                    //公司
                    $this->getPlatformAuthRule($user);
                    break;
                case 2:
                    //平台
                    $this->getPlatformAuthRule($user);
                    break;
                case 5:
                    //社区（前端默认固定的权限）
                    break;
                default:
                    $this->getAuthRule($user);
            }
            return success($user);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 判断使用状态
     * @param $data
     * @return bool
     */
    public function UseStatus($data): bool
    {
        return $data && $data['end_time'] > time() && $data['status'] == 1;
    }

    /**
     * 登录日志
     * @param $user
     * @return bool
     */
    public function LoginLog($user): bool
    {
        return Queue::push(\app\job\CronJob::class, [
            'method' => 'LoginLog',
            'data' => [
                'company_id' => $user['company_id'],
                'areas_id' => $user['areas_id'],
                'unit_id' => $user['unit_id'],
                'id' => $user['id'],
                'ip' => (string) $this->getIp(),
                'ua' => (string) $this->request->server('HTTP_USER_AGENT')??'',
            ],
        ], 'CronJob');
    }

    /**
     * 下级单位
     * @param $user
     * @return void
     */
    public function SubsetUnit(&$user): void
    {
        if ($user['type'] == 1) {
            //公司
            $user['subset_unit'] = $this->UnitModel->where('company_id', '=', $user['company_id'])->column('id');
        }else{
            switch ($user['level']) {
                case 1:
                    //省
                    $user['subset_unit'] = $this->UnitModel->where([
                        ['company_id', '=', $user['company_id']],
                        ['province_id', '=', $user['areas_id']]
                    ])->column('id');
                    break;
                case 2:
                    //市
                    $user['subset_unit'] = $this->UnitModel->where([
                        ['company_id', '=', $user['company_id']],
                        ['city_id', '=', $user['areas_id']]
                    ])->column('id');
                    break;
                case 3:
                    //区
                    $user['subset_unit'] = $this->UnitModel->where([
                        ['company_id', '=', $user['company_id']],
                        ['area_id', '=', $user['areas_id']]
                    ])->column('id');
                    break;
            }
        }
    }

    /**
     * 权限规则
     * @param $user
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAuthRule(&$user): void
    {
        if ($user['role_id'] > 0) {
            //普通账号
            $RoleModel = new RoleModel();
            $role = $RoleModel->where('id', '=', $user['role_id'])->field('name,rules')->find();
            $user['rule'] = $role['rules'] ?? '';
            $user['role_name'] = $role['name'] ?? '';
        } else {
            $user['role_name'] = '超级管理员';
            switch ($user['type']) {
                case 1:
                    //公司
                    $user['rule'] = $user['company']['rules'] ?? '';
                    break;
                case 2:
                    //平台
                    $user['rule'] = $user['platform']['rules'] ?? '';
                    break;
                case 3:
                    //单位
                    $user['rule'] = $user['unit']['rules'] ?? '';
                    break;
                default:
                    break;
            }
        }
        $AuthRuleModel = new AuthRuleModel();
        $user['menu'] = $AuthRuleModel->getMenu($user['rule']);
    }

    /**
     * 获取平台权限规则
     * @param $user
     * @return void
     */
    public function getPlatformAuthRule(&$user): void
    {
        $PlatformAuthRuleModel = new PlatformAuthRuleModel();
        $user['menu'] = $PlatformAuthRuleModel->getMenu();
    }

    /**
     * 账号登录
     * @return false|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, $this->mode->usernameLoginValidate());
            $user = $this->mode->where('username', '=', $param['username'])->find();
            if (!$user) throw new \Exception('账号或密码错误！');
            $newPassword = encrypt_password($param['password']);
            if ($user['password'] != $newPassword) throw new \Exception('账号或密码错误！');
            if ($user['status'] != 1) throw new \Exception('账号异常！');
            if ($user['is_login'] != 1) throw new \Exception('该账号已关闭账号登录！');
            return $this->getUserInfo($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 手机登录发送验证码
     * @return false|string
     */
    public function sendCode(): bool|string
    {
        $param = $this->request->param();
        $this->validate($param, [
            'phone|手机号' => 'require|mobile',
        ]);
        $code = qCode(6, 2);
        $mail = new Mail();
        $result = $mail->sendSMSInform($param['phone'], $code);
        if ($result) {
            // 将验证码放入Redis缓存中  有效时间为5分钟
            cache('phoneCodeLogin_' . md5($code . $param['phone']), 1, 300);
            return success('发送成功！');
        } else {
            return error('发送失败！');
        }
    }

    /**
     * 手机号登录
     * @return false|string
     */
    public function phoneLogin(): bool|string
    {
        try {
            $param = $this->request->param();
            //验证参数
            $this->validate($param, $this->mode->phoneLoginValidate());
            //验证手机验证码
            if (!cache('phoneCodeLogin_' . md5($param['code'] . $param['phone'])))
                throw new \Exception('手机验证码错误！');
            //获取用户信息
            $user = $this->mode->where('backup_phone', '=', $param['phone'])->find();
            if (!$user) throw new \Exception('账号不存在！');
            if ($user['status'] != 1) throw new \Exception('账号异常！');
            if ($user['is_code'] != 1) throw new \Exception('该账号已关闭短信登录！');
            return $this->getUserInfo($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 生成微信登录二维码
     * @return bool|string
     */
    public function getWxCode(): bool|string
    {
        $token = $this->request->param('token');
        $url = get_http_url() . '/common/wx/getCode?token=WxLogin_' . $token;
        $qrCode = QrCode::create($url)
            // 内容编码
            ->setEncoding(new Encoding('UTF-8'))
            // 内容区域大小
            ->setSize(200)
            // 内容区域外边距
            ->setMargin(0);
        // 生成二维码数据对象
        $result = (new PngWriter)->write($qrCode);
        $dataUri = $result->getDataUri();
//        return '<img src="'.$dataUri.'" alt="二维码">';
        return success($dataUri);
    }

    /**
     * 获取二维码登录信息
     * @return bool|string
     */
    public function getWxLoginInfo(): bool|string
    {
        try {
            $token = $this->request->param('token');
            $openid = cache('WxLogin_' . $token);
            if (!$openid) throw new \Exception('参数错误！');
            cache('WxLogin_' . $token,null);
            $user = $this->mode->where('openid', '=', $openid)->find();
            if (!$user) throw new \Exception('参数错误！');
            if ($user['status'] != 1) throw new \Exception('账号异常！');
            if ($user['is_scan'] != 1) throw new \Exception('该账号已关闭扫码登录！');
            return $this->getUserInfo($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 发送手机验证码-找回密码
     * @return false|string
     */
    public function RetrievePasswordSendCode(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'phone|手机号' => 'require|mobile',
            ]);
            $code = qCode(6, 2);
            $mail = new Mail();
            if (!$mail->sendSMSInform($param['phone'], $code)) throw new \Exception('发送失败！');
            // 将验证码放入Redis缓存中  有效时间为5分钟
            cache('phoneCodeRetrievePassword_' . md5($code . $param['phone']), 1, 300);
            return success('发送成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 短信找回密码
     * @return bool|string
     */
    public function smsRetrievePassword(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'phone|手机号' => 'require|mobile',
                'code|手机验证码' => 'require',
                'username|账号' => 'require',
                'password|密码' => 'require'
            ]);
            //验证手机验证码
            if (!cache('phoneCodeRetrievePassword_' . md5($param['code'] . $param['phone'])))
                throw new \Exception('手机验证码错误！');
            $UserModel = new UserModel();
            $user = $UserModel->where([
                ['backup_phone', '=', $param['phone']],
                ['username', '=', $param['username']]
            ])->find();
            if (!$user) throw new \Exception('账号不存在！');
            $user->save([
                'password' => encrypt_password($param['password'])
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 申诉找回密码
     * @return bool|string
     */
    public function appealRetrievePassword(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'username|账号' => 'require',
                'appeal_reason|申诉理由' => 'require',
                'province_id|省' => 'require',
//                'city_id|市' => 'require',
//                'area_id|区' => 'require',
                'unit_id|单位' => 'require',
                'department_id|部门' => 'require',
            ]);
            $UserModel = new UserModel();
            $user = $UserModel->where([
                ['username', '=', $param['username']],
                ['province_id', '=', $param['province_id']],
                ['city_id', '=', $param['city_id']],
                ['area_id', '=', $param['area_id']],
                ['unit_id', '=', $param['unit_id']],
                ['department_id', '=', $param['department_id']],
            ])->find();
            if (!$user) throw new \Exception('关联信息有误,未找到对应账号!');
            $user->status = 3;
            $user->appeal_reason = $param['appeal_reason'];
            $user->save();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 注册账号（普通用户）
     * @return bool|string
     */
    public function RegisterAccount(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'username|账号'  =>  'require|length:8,18|alphaNum',
                'password|密码'  =>  'require|length:8,18',
                'name|姓名' => 'require',
//                'age|年龄' => 'require',
                'sex|性别' => 'require',
                'province_id|省' => 'require',
//                'city_id|市' => 'require',
//                'area_id|区' => 'require',
                'unit_id|单位' => 'require',
                'department_id|部门' => 'require',
//                'id_card|身份证号' => 'require',
//                'user_number|用户编号' => 'require',
            ],[
                'username.require' => '账号不能为空',
                'username.length'     => '账号长度不符合要求，8-18位字符',
                'username.alphaNum'     => '账号格式不符合要求，字母或数字',
                'password.require'        => '密码不能为空',
                'password.length'        => '密码长度不符合要求，8-18位字符',
            ]);
            $unit = $this->UnitModel->field('id,company_id,areas_id,user_num,add_user_num')->find($param['unit_id']);
            if (!$unit) throw new \Exception('参数错误！');
            $unit->add_user_num++;
            if ($unit->add_user_num > $unit->user_num) throw new \Exception('普通用户已超出单位限制！');
            $unit->save();
            $RoleModel = new RoleModel();
            $role_id = $RoleModel->where([
                ['unit_id', '=', $param['unit_id']],
                ['mode', '=', 3]
            ])->value('id');
            if (!$role_id) throw new \Exception('参数错误！');
            $UserModel = new UserModel();
            $uid = $UserModel->where('username', '=', $param['username'])->value('id');
            if ($uid) throw new \Exception('账号已存在！');
            $param['company_id'] = $unit['company_id'];
            $param['areas_id'] = $unit['areas_id'];
            $param['role_id'] = $role_id;
            $param['role_mode'] = 3;
            $param['type'] = 4;
            $param['time'] = time();
            $param['password'] = encrypt_password($param['password']);
            $UserService = new UserService($this->app);
            $param['avatar'] = $UserService->getDefaultAvatar($param['sex'] == 1 ? 'male' :'female');
            if (!$UserModel->insert($param)) throw new \Exception('注册失败！');
            $this->mode->commit();
            return success();
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位名称获取部门信息
     * @return bool|string
     */
    public function UnitNameGetDepartmentInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', '=', $param['name']];
            }
            if (!empty($param['id'])) {
                $where[] = ['id', '=', $param['id']];
            }
            if (empty($where)) {
                return success([
                    'unit_id' => 0,
                ]);
            }
            return success([
                'unit_id' => $this->UnitModel->where($where)->value('id'),
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 单位名称获取部门信息-手机端
     * @return bool|string
     */
    public function UnitNameGetDepartmentInfo2(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', '=', $param['name']];
            }
            if (!empty($param['id'])) {
                $where[] = ['id', '=', $param['id']];
            }
            if (empty($where)) throw new \Exception('参数错误！');
            $unit_info = $this->UnitModel->where($where)->find();
            if (!$unit_info) throw new \Exception('未找到该单位！');
            $DepartmentModel = new DepartmentModel();
            $department = $DepartmentModel->where('unit_id', '=', $unit_info['id'])->select()->toArray();
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $unit_info['id']],
                ['key','=','department_management']
            ])->value('value')??'';
            $config = json_decode($config,true);
            return success([
                'unit_info' => $unit_info,
                'department' => buildTree($department),
                'type' => $config['type']
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 省市区获取单位信息
     * @return bool|string
     */
    public function AreasGetUnitInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'province_id|省' => 'require',
                'city_id|市' => 'require',
                'area_id|区' => 'require',
            ]);
            $data = $this->UnitModel->where([
                ['province_id', '=', $param['province_id']],
                ['city_id', '=', $param['city_id']],
                ['area_id', '=', $param['area_id']],
            ])->field('id,index_name as name')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 身份证登录
     * @return bool|string
     */
    public function idCardLogin(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'cNo|身份证号' => 'require',
                'cName|名称' => 'require',
            ]);
            $user = $this->mode->where([
                ['id_card','=',$param['cNo']],
                ['name','=',$param['cName']]
            ])->find();
            if (!$user) throw new \Exception('参数错误！');
            if ($user['status'] != 1) throw new \Exception('账号异常！');
//            if ($user['is_scan'] != 1) throw new \Exception('该账号已关闭扫码登录！');
            return $this->getUserInfo($user);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取所有省市区
     * @return false|string
     */
    public function getAllAreas(): bool|string
    {
        try {
            $AreasModel = new AreasModel();
            $data = $AreasModel->field('id,name,pid,level')->select()->toArray();
            if (empty($data)) return success();
            $back = array();
            foreach ($data as $v){
                $back[$v['id']]=$v;
            }
            $back[0]=[];
            foreach ($back as &$item){
                if (isset($item['pid'])){
                    $back[$item['pid']]['child'][]=&$item;
                }
            }
            return success($back[0]['child']);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 二维码-部门 任务-注册账号
     * @return bool|string
     */
    public function codeTaskRegister(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'username|账号'  =>  'require|length:8,18|alphaNum',
                'password|密码'  =>  'require|length:8,18',
                'name|姓名' =>  'require',
                'sex|性别' =>  'require',
            ],[
                'username.require' => '账号不能为空',
                'username.length'     => '账号长度不符合要求，8-18位字符',
                'username.alphaNum'     => '账号格式不符合要求，字母或数字',
                'password.require'        => '密码不能为空',
                'password.length'        => '密码长度不符合要求，8-18位字符',
            ]);
            if($this->mode->where('username','=',$param['username'])->value('id')) throw new \Exception('账号已存在！');
            $TaskModel = new TaskModel();
            $info = $TaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $unitInfo = $this->UnitModel->find($info['unit_id']);
            if (!$unitInfo) throw new \Exception('参数错误！');
            $unitInfo->add_user_num++;
            if ($unitInfo->add_user_num > $unitInfo->user_num) throw new \Exception('普通用户已超出单位限制！');
            $unitInfo->save();
            $RoleModel = new RoleModel();
            $role_id = $RoleModel->where([
                ['unit_id','=',$info['unit_id']],
                ['mode','=',3]
            ])->value('id');

            $UserService = new UserService($this->app);
            if ($param['sex'] == 1) {
                $avatar = $UserService->getDefaultAvatar('male');
            } else {
                $avatar = $UserService->getDefaultAvatar('female');
            }
            $platform_id = $this->PlatformModel->where([
                ['company_id','=',$unitInfo['company_id']],
                ['areas_id','=',$unitInfo['areas_id']],
            ])->value('id');
            $userInfo = [
                'company_id' => $unitInfo['company_id'],
                'areas_id' => $unitInfo['areas_id'],
                'platform_id' => $platform_id,
                'unit_id' => $unitInfo['id'],
                'department_id' => $info['department_id'],
                'role_id' => $role_id,
                'role_mode' => 3,
                'type' => 4,
                'username' => $param['username'],
                'password' => encrypt_password($param['password']),
                'name' => $param['name'],
                'avatar' => $avatar,
                'level' => $unitInfo['level'],
                'province_id' => $unitInfo['province_id'],
                'city_id' => $unitInfo['city_id'],
                'area_id' => $unitInfo['area_id'],
                'province_name' => $unitInfo['province_name'],
                'city_name' => $unitInfo['city_name'],
                'area_name' => $unitInfo['area_name'],
                'sex' => $param['sex'],
                'age' => $param['age']??0,
                'time' => time()
            ];
            $userInfo['id'] = $this->mode->insertGetId($userInfo);
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $ratingScaleData = $TaskRatingScaleModel->where('task_id','=',$param['id'])->select()->toArray();
            foreach ($ratingScaleData as $v){
                $task_user[] = [
                    'task_id' => $param['id'],
                    'rating_scale_id' => $v['rating_scale_id'],
                    'uid' => $userInfo['id'],
                    'time' => time()
                ];
            }
            if (!empty($task_user)){
                $TaskUserModel = new TaskUserModel();
                $TaskUserModel->insertAll($task_user);
            }
            //任务用户完成数加1
            $info->user_count++;
            $info->user_complete_rate = number_format(($info->user_complete_num / $info->user_count) * 100, 2);
            $info->save();
            $this->mode->commit();
            return $this->getUserInfo($userInfo);
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 验证任务二维码code，并返回任务id
     * @return bool|string
     */
    public function verifyTaskCode(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'code|code' => 'require',
            ]);
            if (!cache($param['code'])) throw new \Exception('二维码已失效！');
            return success(cache($param['code']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取随机token
     * @return bool|string
     */
    public function getToken(): bool|string
    {
        try {
            $token = md5(time() . uniqid());
            return success([
                'token' => $token,
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 当前级别部门
     * @return bool|string
     */
    public function currentLevel(): bool|string
    {
        try {
            $param = $this->request->param();
            if (empty($param['unit_id'])){
                $param['unit_id'] = $this->userData['unit_id'];
            }
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->field('id,name')->where([
                ['unit_id','=',$param['unit_id']],
                ['pid','=',$param['pid']??0]
            ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 同步加密狗
     * @return bool|string
     */
    public function setKey(): bool|string
    {
        try {
            $param = $this->request->param();
            if (!empty($param['key']) && $param['key'] == env('JMG_KEY') && env('JMG_STATUS')){
                cache(env('REDIS_PROJECT').'jmg_key',$param['key'],3);
            }else{
                if (cache(env('REDIS_PROJECT').'jmg_key') != env('JMG_KEY') && env('JMG_STATUS')){
                    throw new \Exception('请插入加密狗！');
                }
            }
            return success(env('JMG_STATUS'));
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}
